package com.nineclock.message.service.impl;

import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.message.dto.NcMessageDTO;
import com.nineclock.message.service.MessageService;
import com.nineclock.message.config.JPushManager;
import com.nineclock.message.pojo.NcMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class MessageApplicationImpl implements MessageService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    JPushManager pushManager;

    @Override
    public Boolean pushSingleMessage(NcMessage message) throws Exception {
        //1. 把收到的消息存储到mongodb中
        mongoTemplate.save(message);

        //推送消息给主管理员
        //1.参数 标题  2. 推送的内容  3. 推送的目标 4. 自定义内容 一般为null
        pushManager.sendNotificationByAlias(message.getTitle(),message.getContent(),message.getTargets(),null);

        return true;
    }

    @Override
    public List<NcMessage> findMessageRecord(NcMessageDTO messageDTO) {

        if (messageDTO==null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //查询条件
        Query query = new Query();

        if (messageDTO.getId() !=null) {
            query.addCriteria(Criteria.where("_id").is(messageDTO.getId()));
        }

        if (messageDTO.getType() !=null) {//消息类型
            query.addCriteria(Criteria.where("messageType").is(messageDTO.getType()));
        }

        if (messageDTO.getTargetId() !=null) {//审批人id
            query.addCriteria(Criteria.where("approveUserId").is(messageDTO.getTargetId()));
        }

        if (messageDTO.getUserId() !=null) {//申请人id
            query.addCriteria(Criteria.where("applyUserId").is(messageDTO.getUserId()));
        }

        //排序, 根据审核状态升序排序（必须排序，否则会不显示）
        query.with(Sort.by(Sort.Direction.ASC, "approveStatue"));

        //查询返回类型 .class
        List<NcMessage> messageList = mongoTemplate.find(query, NcMessage.class);


        return messageList;
    }

    //更新mongo
    @Override
    public void updateMessageWithApproved(String messageId) {
        Query query =  new Query();
        query.addCriteria(Criteria.where("_id").is(messageId));

        Update update = new Update();
        update.set("useStatus",1);
        update.set("approveStatue",1);
        mongoTemplate.updateFirst(query,update,NcMessage.class);
    }


}
